namespace PHSRAG.Insight21.FormsManagement.Controls
{
	using System;
	using System.Data;
	using System.Drawing;
	using System.Web;
	using System.Web.UI.WebControls;
	using System.Web.UI.HtmlControls;
	using System.Collections;

	/// <summary>
	///	DropDownMultiSelectItemEditor helps in creating a question with a predefined set of options. These options are displayed in a dropdownlist box in the MultiSelection control.
	/// </summary>
	public partial class DropDownMultiSelectItemEditor : System.Web.UI.UserControl
	{
		#region Constants
		private const string ItemOptionsSourceKey = "ItemOptionsKey_14FD15B1-D3C4-47ce-B376-4025A25EBB9E";
		#endregion

		#region Instance Variables (private)
		private	Policy.ICachePolicy		pageCachePolicy;
		private Policy.ICachePolicy		cachePolicy;
		private QuestionnaireItem dropDownMultiSelectQuestion;
		private DataTable itemOptionsSource;
		#endregion

		#region Instance Varibles (Protected)
		/// <summary>emits a warning message to the user</summary>
		protected PHSRAG.WebControls.Annunciator annunciator;
		#endregion

		#region Properties
		/// <summary>
		/// Sets the annunciator instance used to display any information to the user. This must be set by the control's container
		/// </summary>
		public PHSRAG.WebControls.Annunciator Annunciator
		{
			set { annunciator = value; }
		}
		#endregion

		#region Events (Page)
		/// <summary>
		/// Populates data into corresponding controls.
		/// </summary>
		/// <param name="sender">Control that raised the event.</param>
		/// <param name="e">Arguments associated with the event.</param>
		protected void OnPageLoad(object sender, System.EventArgs e)
		{
			if (annunciator == null)
				throw new Exception("Annunciator is not initialized.");

			annunciator.Message = string.Empty;
			if (!IsPostBack)
			{
				ItemEditor containerPage = (ItemEditor)Page;
				if (containerPage.SelectedQuestionnaireItemId != 0)
				{
					Hashtable questionnairesList = (Hashtable)cachePolicy.GetCachedObject(Keys.QuestionnaireObjectsKey);
					Questionnaire questionnaire = (Questionnaire)questionnairesList[containerPage.SelectedQuestionnaireID];
					QuestionnaireVersion questionnaireVersion = questionnaire.GetQuestionnaireVersionById( containerPage.SelectedQuestionnaireVersionID );
					dropDownMultiSelectQuestion = questionnaireVersion.GetQuestionnaireItemById( containerPage.SelectedQuestionnaireItemId );
					baseQuestionItemEditor.ItemName = dropDownMultiSelectQuestion.Name;
					baseQuestionItemEditor.ItemText = dropDownMultiSelectQuestion.Text;
					baseQuestionItemEditor.Required = dropDownMultiSelectQuestion.Required;
					baseQuestionItemEditor.ValidationMessage = dropDownMultiSelectQuestion.ValidationMessage;
					baseQuestionItemEditor.HasSeparator = dropDownMultiSelectQuestion.HasSeparator;
					baseQuestionItemEditor.IsVersionDeployed = questionnaireVersion.IsDeployed;
					itemOptionEditor.IsVersionDeployed = questionnaireVersion.IsDeployed;
				}
				else
				{
					dropDownMultiSelectQuestion = new QuestionnaireItem(cachePolicy);
					dropDownMultiSelectQuestion.Type = QuestionnaireItem.DropDownMultiSelectItemType;
					dropDownMultiSelectQuestion.VersionId = containerPage.SelectedQuestionnaireVersionID;
					dropDownMultiSelectQuestion.Options = new ArrayList();
				}
				ArrayList options = new ArrayList();
				if (dropDownMultiSelectQuestion.OptionsRefDomain == null || dropDownMultiSelectQuestion.OptionsRefDomain == string.Empty)
				{
					options = dropDownMultiSelectQuestion.Options;
					
				}
				pageCachePolicy.Cache(Keys.ItemOptionsKey, options);

				pageCachePolicy.Cache(Keys.QuestionnaireItemKey,  dropDownMultiSelectQuestion);
				pageCachePolicy.Cache(ItemOptionsSourceKey, itemOptionsSource);
			}
			else
			{
				itemOptionsSource = (DataTable)pageCachePolicy.GetCachedObject(ItemOptionsSourceKey);
				dropDownMultiSelectQuestion = (QuestionnaireItem)pageCachePolicy.GetCachedObject(Keys.QuestionnaireItemKey);
			}
			
		}

		#endregion

		#region Web Form Designer generated code
		/// <summary>
		/// Page Initialization
		/// </summary>
		/// <param name="e">Arguments associated with the event.</param>
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
			pageCachePolicy = (Policy.ICachePolicy)Session[Policy.Names.PageCachePolicyKey];
			cachePolicy = (Policy.ICachePolicy)Session[Policy.Names.CachePolicyKey];
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.OnPageLoad);

		}
		#endregion

		#region Events (controls)
		/// <summary>
		/// Verifies that the question name and all the item option values are unique. If so,
		/// saves the question and adds it to the questions collection (only if the question being saved is a new one)
		/// </summary>
		/// <param name="sender">Control that raised the event.</param>
		/// <param name="e">Arguments associated with the event.</param>
		protected void OnSaveQuestionnaireItem(object sender, System.EventArgs e)
		{
			try
			{
				dropDownMultiSelectQuestion.Name = baseQuestionItemEditor.ItemName;
				ItemEditor containerPage = (ItemEditor)Page;
				Hashtable questionnairesList = (Hashtable)cachePolicy.GetCachedObject(Keys.QuestionnaireObjectsKey);
				Questionnaire questionnaire = (Questionnaire)questionnairesList[containerPage.SelectedQuestionnaireID];
				QuestionnaireVersion questionnaireVersion = questionnaire.GetQuestionnaireVersionById( containerPage.SelectedQuestionnaireVersionID );
				if (containerPage.SelectedQuestionnaireItemId == 0 && questionnaireVersion.DoesItemNameExists(dropDownMultiSelectQuestion.Name))
				{
					annunciator.Message = "Item name already exists. Please enter another name";
					return;
				}
				try
				{
					itemOptionEditor.UpdateSource(dropDownMultiSelectQuestion.Options, dropDownMultiSelectQuestion.Id);
				}
				catch(Exception ex)
				{
					annunciator.Message = ex.Message;
					return;
				}
				dropDownMultiSelectQuestion.Text = baseQuestionItemEditor.ItemText;
				dropDownMultiSelectQuestion.Required = baseQuestionItemEditor.Required;
				dropDownMultiSelectQuestion.ValidationMessage = (dropDownMultiSelectQuestion.Required) ? baseQuestionItemEditor.ValidationMessage :	string.Empty;
				dropDownMultiSelectQuestion.HasSeparator = baseQuestionItemEditor.HasSeparator;
				//For new questions, set the order to one more than the existing maximum order
				if (containerPage.SelectedQuestionnaireItemId == 0)
				{
					dropDownMultiSelectQuestion.Order = questionnaireVersion.GetMaxItemOrder() + 1;
				}

				dropDownMultiSelectQuestion.Save(Utility.DataAccess.ConnectionString);

				questionnaireVersion.Items = null;

				Response.Redirect(Utility.Settings.GetKeyValue("SubNavigation.Admin.Humans.FormEditorURL", "FormEditor.aspx"), false);
			}
			catch(Exception ex)
			{
				DisplayExceptionReport(ex);
			}

		}


		/// <summary>
		/// Redirects the user to the FormEditor page
		/// </summary>
		/// <param name="sender">Control that raised the event.</param>
		/// <param name="e">Arguments associated with the event.</param>
		protected void OnCancelQuestionnaireItem(object sender, System.EventArgs e)
		{
			Response.Redirect(Utility.Settings.GetKeyValue("SubNavigation.Admin.Humans.FormEditorURL", "FormEditor.aspx"));
		}
		#endregion

		#region Private methods
		/// <summary>
		/// Displays an error message on the screen to the user with the exception, and all
		/// inner exception messages.
		/// </summary>
		/// <param name="ex">The exception to report on</param>
		private void DisplayExceptionReport(Exception ex)
		{
			annunciator.Title = InsightUtilities.Constants.Annunciator.Title;
			annunciator.Message = Utility.ExceptionReport.GetExceptionInfo(ex, false);
		}
		#endregion
	}
}
